package com.sharedlease.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sharedlease.entity.Message;
import com.sharedlease.entity.R;
import com.sharedlease.entity.Chat;
import com.sharedlease.service.ChatService;
import com.sharedlease.service.impl.ChatServiceImpl;
import com.sharedlease.websocket.ScheduleUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.sharedlease.websocket.MessageConstant.RENT_REMINDER;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴钟富
 * @since 2021-03-27
 */
@RestController
@Api(tags = "聊天记录相关接口")
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    public ChatService chatService;

    @GetMapping("/getById/{id}")
    @ApiOperation("根据一个id查询聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "要查询的聊天记录id", defaultValue = "1"),

    }
    )
    public Chat getById(@PathVariable Long id) {
        Chat chat = chatService.getById(id);
        return chat;
    }

    @GetMapping("/list")
    @ApiOperation("查询全部聊天记录")
    public List<Chat> list() {
        List<Chat> list = chatService.list(null);
        return list;
    }

    @PostMapping("/save")
    @ApiOperation("新增一条聊天记录")
    public R save(@RequestBody Chat chat) {

        return R.operate(chatService.save(chat));
    }

    @PutMapping("/update")
    @ApiOperation("根据id更改一条聊天记录")
    R update(@RequestBody Chat chat) {
        if (chatService.updateById(chat)) {
            return R.ok();
        }
        return R.error();
    }

    @PutMapping("/updateRead_timeById/{id}/{has_read}")
    @ApiOperation("根据id更改聊天记录是否已读状态,1为已读，默认为未读（0）")
    R updateEnd_timeById(@PathVariable Long id,@PathVariable Integer has_read ) {
        UpdateWrapper<Chat> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        Chat chat = new Chat();
        chat.setHasRead(has_read);
        if (chatService.update(chat,wrapper)) {
            return R.ok();
        }

        return R.error();
    }

    @PutMapping("/updateRead_timeTwoIds/{sourceId}/{destId}/{has_read}")
    @ApiOperation("根据发送者id和接受者id更改聊天记录是否已读状态,1为已读，默认为未读（0）")
    R updateRead_timeTwoIds(@PathVariable Long sourceId,@PathVariable Long destId,@PathVariable Integer has_read ) {
        UpdateWrapper<Chat> wrapper = new UpdateWrapper<>();
        wrapper.eq("source_id",sourceId);
        wrapper.eq("dest_id",destId);
        Chat chat = new Chat();
        chat.setHasRead(has_read);
        if (chatService.update(chat,wrapper)) {
            return R.ok();
        }

        return R.error();
    }

    @GetMapping("/getChatsByTwoIds/{id1}/{id2}")
    @ApiOperation("根据两个id查询聊天记录")
    public List<Chat> list(@PathVariable Long id1,@PathVariable Long id2) {
        ChatServiceImpl chatService = new ChatServiceImpl();
        List<Chat> list = new ArrayList<Chat>();
        list=chatService.getChatsFromRedisByTwoIds(id1, id2);
        if (list==null||list.size()<1){
            QueryWrapper<Chat> wrapper = new QueryWrapper<>();
            wrapper.eq("source_id",id1+"") .eq("dest_id",id2+"")
                    .or()
                    .eq("dest_id",id1+"") .eq("source_id",id2+"");
           list = this.chatService.list(wrapper);
           chatService.saveAllChatsToRedis(list);
            System.out.println("redis没有，直接从mysql中拿并且存到redis");
        }
        System.out.println("redis中有，直接从redis中拿并返回");
        return list;

    }

    @GetMapping("/getNotReadChatsByDestId/{destId}")
    @ApiOperation("根据用户id查询未读聊天记录")
    public List<Chat> list(@PathVariable Long destId) {
        ChatServiceImpl chatService1 = new ChatServiceImpl();
        List<Chat> list = chatService1.getChatsByDestId(destId);
        if (list==null||list.size()<1) {
            QueryWrapper<Chat> wrapper = new QueryWrapper<>();
            wrapper.eq("dest_id", destId + "").eq("has_read", 0 + "");
            list = this.chatService.list(wrapper);
            chatService1.saveAllChatsToRedis(chatService.list(null));
            System.out.println("redis中没有根据目的id查询得到的聊天记录，从mysql中拿，并将所有聊天记录存到redis");
        }
        System.out.println("redis中已有聊天记录");
        return list;
    }



    @DeleteMapping("/removeById/{id}")
    @ApiOperation("根据id删除一条聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "要删除的聊天记录id", defaultValue = "-1"),

    }
    )
    R removeById(@PathVariable Long id) {

        return R.operate(chatService.removeById(id));
    }

    @PostMapping("/sendTimeRent/{seconds}/{merchantId}/{userId}")
    @ApiOperation("多少秒后，向某厂商向某用户发送租赁即将到期的提醒")
    public R sendTimeRent(@PathVariable Integer seconds,@PathVariable Long merchantId,@PathVariable Long userId){
        long id = IdWorker.getId();
        Chat chat = new Chat();
        chat.setId(id);
        chat.setSourceId(merchantId);
        chat.setSourceName("租赁即将到期通知");
        chat.setDestId(userId);
        chat.setMessage("您有即将到期的产品，请进入订单页面续租或退租");
        chat.setHasRead(0);
        try {

            ScheduleUtil.sendTimeRent(DateUtil.offsetSecond(DateUtil.parse(DateUtil.now()), seconds), chat);
            return R.ok();
        } catch (SchedulerException | InterruptedException e) {
            e.printStackTrace();
            return R.error();
        }
    }


}

